<template>
  <a-modal :maskClosable="false" :title="title" :width="1200" :bodyStyle="{
    padding: '0 24px',
  }" :visible="visible" @ok="handleOk" @cancel="handleCancel" cancelText="关闭">
    <a-card :bordered="false" :bodyStyle="{
      padding: '10px 24px',
    }">
      <a-row :gutter="20">
        <a-col class="gutter-row" :span="24">
          <a-row :gutter="20">
            <a-col class="gutter-row" :span="16">
              <a-input placeholder="模板名称" v-model="nodeName" />
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-button @click="searchByquery" type="primary" icon="search">查询</a-button>
              <a-button @click="searchReset(1)" style="margin-left: 8px" icon="redo">重置</a-button>
            </a-col>
          </a-row>
          <a-row style="margin-top:20px">
            <a-col class="gutter-row" :span="24">
              <a-table ref="table" rowKey="id" :scroll="scrollTrigger" :columns="columns" :dataSource="dataSource"
                :loading="loading" :pagination="ipagination" :rowSelection="{
                  selectedRowKeys: selectedRowKeys,
                  onSelectAll: onSelectAll,
                  onSelect: onSelectOne,
                  onChange: onSelectChange,
                  type: multi == true ? 'checkbox' : 'radio'
                }" @change="handleTableChange" class="j-table-force-nowrap" wrapClassName="ant-modal-cust-warp">
              </a-table>
            </a-col>
          </a-row>
        </a-col>
      </a-row>

    </a-card>
  </a-modal>
</template>

<script>
import { filterObj } from '@/utils/util'
import { queryDepartTreeList, searchByKeywords } from '@/api/api'
import { getAction } from '@/api/manage'
export default {
  name: 'SelectProgressPaymentNodeInputModal',
  components: {
  },
  props: ['multi', 'urlList'],
  data() {
    return {
      title: '关联任务节点1',
      queryParam: {},
      nodeName:'',
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
          customCell: (record, index) => {
            let that = this
            return {
              on: {
                click: () => {
                  console.log(record, index)
                  that.selectedRowKeys = [];
                  that.selectedRowKeys.push(record.id);
                  that.choseObj = [];
                  that.choseObj.push(record);
                  // if(that.selectedRowKeys.indexOf(record.id)> -1) {
                  //   that.selectedRowKeys.splice(that.selectedRowKeys.indexOf(record.id), 1)
                  //   this.choseObj.splice(that.selectedRowKeys.indexOf(record.id), 1)
                  // } else {
                  //   that.selectedRowKeys.push(record.id)
                  //   that.choseObj.push(record)
                  // }

                  // if (JSON.stringify(that.choseObj).indexOf(JSON.stringify(record)) == -1) {
                  //   that.choseObj.push(record)
                  //   console.log("不存在");
                  // } else {
                  //   console.log("已存在");
                  //   let index = this.choseObj.indexOf(record)
                  //   this.choseObj.splice(index, 1)
                  // }
                }
              }
            }
          }
        },
        {
          title: '节点名称',
          align: 'center',
          dataIndex: 'nodeName',
          scopedSlots: { customRender: 'nodeName' },
          customCell: (record, index) => {
            let that = this
            return {
              on: {
                click: () => {
                  console.log(record, index)
                  that.selectedRowKeys = [];
                  that.selectedRowKeys.push(record.id);
                  that.choseObj = [];
                  that.choseObj.push(record);
                  // if(that.selectedRowKeys.indexOf(record.id)> -1) {
                  //   that.selectedRowKeys.splice(that.selectedRowKeys.indexOf(record.id), 1)
                  //   this.choseObj.splice(that.selectedRowKeys.indexOf(record.id), 1)
                  // } else {
                  //   that.selectedRowKeys.push(record.id)
                  //   that.choseObj.push(record)
                  // }

                  // if (JSON.stringify(that.choseObj).indexOf(JSON.stringify(record)) == -1) {
                  //   that.choseObj.push(record)
                  //   console.log("不存在");
                  // } else {
                  //   console.log("已存在");
                  //   let index = this.choseObj.indexOf(record)
                  //   this.choseObj.splice(index, 1)
                  // }
                }
              }
            }
          }
        },
        {
          title: '节点进度',
          align: 'center',
          dataIndex: 'completeInfo',
          scopedSlots: { customRender: 'completeInfo' },
          customCell: (record, index) => {
            let that = this
            return {
              on: {
                click: () => {
                  that.selectedRowKeys = [];
                  that.selectedRowKeys.push(record.id);
                  that.choseObj = [];
                  that.choseObj.push(record);

                  // if (JSON.stringify(that.choseObj).indexOf(JSON.stringify(record)) == -1) {
                  //   that.choseObj.push(record)
                  //   console.log("不存在");
                  // } else {
                  //   console.log("已存在");
                  //   let index = this.choseObj.indexOf(record)
                  //   this.choseObj.splice(index, 1)
                  // }
                }
              }
            }
          }
        },
      ],
      url: {
        'erpProgressTaskList': '/api/erp/progress/erpProgressTask/list',
        'queryTaskNodeInfoById': '/api/erp/progress/erpProgressContractNode/list',
        'queryValidListByContractId': '/api/erp/progress/erpProgressPaymentNode/queryValidListByContractId'
      },
      dataSource: [],
      choseObj: [],
      departTree: [],
      selectedKeys: [],
      iExpandedKeys: [],
      contractId: '',
      orgCode: '',
      loading: false,
      treeData: [],
      checkedKeys: [],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      scrollTrigger: { x: true },
      selectedRowKeys: [],
      selectionRows: [],
      visible: false,
      toggleSearchStatus: false,
      nodelist: []
    }
  },
  created() {
    // this.loadData()
    // 该方法触发屏幕自适应
    this.resetScreenSize()
    // this.refresh()
    // this.initSource()
  },
  mounted() {
    // this.geterpProgressTaskList()
  },
  methods: {
    // nodeClick(item,index) {
    //   console.log(item,index);
    //   this.getqueryTaskNodeInfoById(item.id)
    // },
    getqueryTaskNodeInfoById(id) {
      var val = '';
      if (id === -1) {
        val = this.contractId
      } else {
        val = id
      }
      let params = {
        contractId: val,
        nodeName: this.nodeName,
        pageNo: 1,
        pageSize: 10000
      }
      getAction(this.url.queryValidListByContractId, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result || []
          console.log(" this.dataSource", this.dataSource);
        }
      })
    },
    // geterpProgressTaskList(id) {
    //   let params = {
    //     contractId: id,
    //     pageNo :1 ,
    //     pageSize:10000
    //   }
    //   getAction(this.url.erpProgressTaskList, params).then((res) => {
    //     if (res.success) {
    //       console.log("left=======",res);
    //       this.nodelist = res.result.records || []
    //       if (res.result.records.length > 0) {
    //         this.getqueryTaskNodeInfoById(res.result.records[0].contractId)
    //       }
    //     }
    //   })
    // },
    add(selectObj, ids) {
      this.visible = true
      this.edit(selectObj, ids)
    },
    edit(selectObj, ids) {
      if (!ids) {
        this.selectedRowKeys = []
      } else {
        this.selectedRowKeys = ids
      }
      if (!selectObj) {
        this.selectionRows = []
      } else {
        this.selectionRows = selectObj
        this.choseObj = selectObj
      }
      if (ids == null && selectObj == null) {
        this.selectionRows = []
        this.choseObj = []
        this.selectedRowKeys = []
      }

      console.log("这是最后辉县收短信接口vjhdfkhj======",this.choseObj);
    },
    loadData(arg, url) {
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.pageEnable = true
      var params = this.getQueryParams() // 查询条件
      params.sysOrgCode = this.orgCode
      let tmpUrl = this.urlList
      if (url) {
        tmpUrl = url
      }
      getAction(tmpUrl, params).then((res) => {
        if (res.success) {
          if (res.result == null) {
            this.dataSource = []
            this.ipagination.total = 0
            return
          }
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
          if (this.orgCode === '') {
            // 第一次打开
          } else {
            for (var i = 0; i < this.dataSource.length; i++) {
              for (var j = 0; j < this.choseObj.length; j++) {
                if (this.choseObj[j].id == this.dataSource[i].id) {
                  this.selectionRows.push(this.dataSource[i])
                  this.selectedRowKeys.push(this.dataSource[i].id)
                  break
                }
              }
            }
          }
          // 判断是否当前页没有数据且不为第一页
          if (this.dataSource.length == 0 && this.ipagination.current != 1) {
            this.ipagination.current = this.ipagination.current - 1
            this.loadData(this.ipagination.current - 1)
          }
          this.loading = false
        } else {
          this.dataSource = []
          this.ipagination.total = 0
        }
      })

    },
    loadTree() {
      var that = this
      that.treeData = []
      that.departTree = []
      queryDepartTreeList().then((res) => {
        if (res.success) {
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            that.treeData.push(temp)
            that.departTree.push(temp)
            that.setThisExpandedKeys(temp)
          }
          this.loading = false
        }
      })
    },
    getQueryParams() {
      let param = Object.assign({}, this.queryParam, this.isorter)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    getQueryField() {
      let str = 'id,'
      for (let a = 0; a < this.columns.length; a++) {
        str += ',' + this.columns[a].dataIndex
      }
      return str
    },
    onSelectAll(selected, selectedRows, changeRows) {
      if (selected === true) {
        for (var a = 0; a < changeRows.length; a++) {
          this.choseObj.push(changeRows[a])
        }
      } else {
        for (var b = 0; b < changeRows.length; b++) {
          this.choseObj.splice(this.choseObj.indexOf(changeRows[b]), 1)
        }
      }
    },
    onSelectOne(record, selected) {
      console.log(record, selected,"record, selectedrecord, selected");
      if (selected === true) {
        if (this.multi) {
          // 多选
          this.choseObj.push(record)
        } else {
          // 单选
          this.choseObj = []
          this.choseObj.push(record)
        }
      } else {
        if (this.multi) {
          // 多选
          var index = -1
          for (var i = 0; i < this.choseObj.length; i++) {
            if (this.choseObj[i].id == record.id) {
              index = i
              break
            }
          }
          if (index >= 0) {
            this.choseObj.splice(index, 1)
          }
        } else {
          // 单选
          this.choseObj = []
        }
      }
    },
    initSource() {
      this.selectedRowKeys = []
      this.selectionRows = []
      this.choseObj = []
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    searchReset() {
      let that = this
      // Object.keys(that.queryParam).forEach(function (key) {
      //   that.queryParam[key] = null
      // })
      // this.dataSource = []
      // this.ipagination.total = 0
      this.nodeName = ''
      that.getqueryTaskNodeInfoById(-1)
      // that.loadData(1)
    },
    handleTableChange(pagination, filters, sorter) {
      // TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      that.getqueryTaskNodeInfoById(-1)
    },
    handleCancel() {
      this.selectionRows = []
      this.selectedRowKeys = []
      this.visible = false
    },
    handleOk() {
      let data = {
        choseObj: this.choseObj,
        cutStatus: this.queryParam.cutStatus
      }
      this.$emit('choseObj', data)
      this.handleCancel()
    },
    searchByquery() {
      // this.loadData(1)
      this.selectionRows = []
      this.selectedRowKeys = []
      this.choseObj = []
      this.getqueryTaskNodeInfoById(-1)
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    onSearch(value) {
      let that = this
      if (value) {
        searchByKeywords({ keyWord: value }).then((res) => {
          if (res.success) {
            that.departTree = []
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.departTree.push(temp)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      } else {
        that.loadTree()
      }
    },
    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    refresh() {
      this.loading = true
      this.loadTree()
    },
    onSelect(selectedKeys, e) {
      if (this.selectedKeys[0] !== selectedKeys[0]) {
        this.selectedKeys = [selectedKeys[0]]
      }
      let record = e.node.dataRef
      // this.selectionRows.push(record.id);
      this.onClearSelected()
      this.open(record)
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    open(record) {
      this.orgCode = record.orgCode
      this.loadData(1)
    },
    // 触发屏幕自适应
    allObj() {
      this.selectedKeys = []
      this.onClearSelected()
      this.orgCode = null
      this.loadData(1)
    },
    resetScreenSize() {
      let screenWidth = document.body.clientWidth
      if (screenWidth < 500) {
        this.scrollTrigger = { x: 800 }
      } else {
        this.scrollTrigger = {}
      }
    },
  }
}
</script>
<style scoped>
.nodestyle {
  cursor: pointer;
}
.nodeactive {
  background: #eee;
}
.ant-card-body .table-operator {
  margin-bottom: 18px;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 15px;
  padding-bottom: 15px;
}

.anty-row-operator button {
  margin: 0 5px;
}

.ant-btn-danger {
  background-color: #ffffff;
}

.ant-modal-cust-warp {
  height: 100%;
}

.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto;
}

.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden;
}

.anty-img-wrap {
  height: 25px;
  position: relative;
}

.anty-img-wrap>img {
  max-height: 100%;
}
</style>
